from orm.entity.Dormitory import Dormitory
from orm.entity.User import User
from orm.persistence import DormitoryUtil
from orm.persistence.DormitoryUtil import dormitoryDeleteUser
from sqlConfig import DBSession


def userLogin(userId, password):
    session = DBSession()
    user = session.query(User).filter_by(userId=userId, password=password).first()
    return user


#  返回值对应内容说明：0表示注册成功，1表示userId已经存在，2表示dormitory已经满了,3表示dormitoryId不存在
def userRegister(userId, userName, password, phone_number, dormitoryId):
    session = DBSession()
    checkUser = session.query(User).filter_by(userId=userId).first()

    checkDormitory = None

    # Id已经被使用
    if checkUser is not None:
        return 1

    if dormitoryId is not None:
        checkDormitory = session.query(Dormitory).filter_by(dormitoryId=dormitoryId).first()
        #  如果宿舍号为不存在，返回3
        if checkDormitory is None:
            return 3

        else:
            checkDormitoryUser = checkDormitory.user4
            # 宿舍已满
            if checkDormitoryUser is not None:
                return 2
    # 注册成功，user表和dormitory表都要更新
    user = User(userId, userName, password, phone_number, dormitoryId, 0)
    session.add(user)
    session.commit()
    DormitoryUtil.domitoryAddUser(dormitoryId, user.userId)
    return 0


def userUpdate(userId, userName, password, phone_number, dormitoryId):
    try:
        session = DBSession()
        user = session.query(User).filter_by(userId=userId).first()
        user.userId = userId
        user.userName = userName
        user.password = password
        user.phone_number = phone_number
        user.dormitoryId = dormitoryId
        session.commit()
        session.close()
        return True

    except:
        return False


def userSearchById(userId):
    session = DBSession()
    user = session.query(User).filter_by(userId=userId).first()
    session.close()
    return user


def userSearchByUserName(userName):
    session = DBSession()
    userList = session.query(User).filter_by(userName=userName).all()
    session.close()
    return userList


def userDeleteByUserId(userId):
    session = DBSession()
    user = session.query(User).filter_by(userId=userId).first()
    # 如果不存在此用户，则返回false
    if user is None:
        session.close()
        return False
    else:
        # 同时要修改宿舍表的信息
        dormitoryId = user.dormitoryId
        session.delete(user)
        session.commit()
        if dormitoryId is not None:
            dormitoryDeleteUser(dormitoryId, userId)
        session.close()
        return True
